# Setup the start zone, end zone, and stage
start = codesters.Rectangle(0, -250, 500, 50, "red")
finish = codesters.Rectangle(0, 250, 500, 50, "green")
stage.disable_all_walls()
# Set up the roads
road_list = [-150, -50, 50, 150]
for value in road_list:
road = codesters.Rectangle(0, value, 500, 50, "gray")
# Setup the player sprite
sprite = codesters.Sprite("turtle1", 0, -240)
sprite.set_size(.2)
sprite.turn_left(90)
# Interval event creates the cars
def interval():
rand_y = random.choice(road_list)
# Send cars to the right
if rand_y == -150 or rand_y == 50:
car = codesters.Sprite("car1", -400, rand_y)
car.turn_right(90)
car.set_size(.5)
car.set_x_speed(2)
# Send cars to the left
if rand_y == -50 or rand_y == 150:
car = codesters.Sprite("car2", 400, rand_y)
car.turn_left(90)
car.set_size(.5)
car.set_x_speed(-2)
stage.event_interval(interval, .5)
# Movement controls for arrow keys
def up_key():
sprite.move_up(20)
stage.event_key("up", up_key)
def down_key():
sprite.move_down(20)
stage.event_key("down", down_key)
def left_key():
sprite.move_left(20)
stage.event_key("left", left_key)
def right_key():
sprite.move_right(20)
stage.event_key("right", right_key)
# Display win/loss as text
result = codesters.Text("")
# Detect collision with cars (loss) or with end zone (win)
def collision(sprite, hit_sprite):
image = hit_sprite.get_image_name()
color = hit_sprite.get_color()
# Win if touching the end zone
if color == "green":
result.set_text("YOU WON!")
result.set_color("green")
# Loss if touching a car
if image == "car1" or image == "car2":
result.set_text("YOU LOST!")
result.set_color("red")
sprite.go_to(0, -250)
sprite.event_collision(collision)
tester = TestManager()
tester.display_success_message("Great job!")
-
Run Code
-
Activity Submitted!
Submit Work
-
Next Activity
-
Stop Running Code
-
Show Chart
-
Show Console
-
Reset Code Editor
-
Codesters How To (opens in a new tab)